package zack.gateway.core.socket.handlers;

import zack.gateway.core.executor.result.SessionResult;
import zack.gateway.core.session.GatewaySession;
import zack.gateway.core.session.GatewaySessionFactory;
import zack.gateway.core.session.defaults.DefaultGatewaySessionFactory;
import zack.gateway.core.socket.BaseHandler;
import zack.gateway.core.socket.agreement.AgreementConstants;
import zack.gateway.core.socket.agreement.GatewayResultMessage;
import zack.gateway.core.socket.agreement.RequestParser;
import zack.gateway.core.socket.agreement.ResponseParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ExecutionException;

public class ProtocolDataHandler extends BaseHandler<FullHttpRequest> {
    private final Logger logger = LoggerFactory.getLogger(GatewayServerHandler.class);

    private final DefaultGatewaySessionFactory gatewaySessionFactory;

    public ProtocolDataHandler(DefaultGatewaySessionFactory gatewaySessionFactory) {
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void session(ChannelHandlerContext channelHandlerContext, Channel channel, FullHttpRequest request) throws ExecutionException, InterruptedException {

        logger.info("网关接收请求 uri：{} method：{}", request.uri(), request.method());


        // 返回信息控制：简单处理
        RequestParser parser = new RequestParser(request);
        String uri = parser.getUri();
        Map<String, Object> requestObj = parser.parse();

        //获取rpc会话
        GatewaySession gatewaySession = gatewaySessionFactory.openSession(uri);

        // 服务泛化调用
        SessionResult result =  gatewaySession.getMapper().$invoke(requestObj) ;

        DefaultFullHttpResponse response = new ResponseParser().parse(result.getCode().equals("0000") ?
                        GatewayResultMessage.buildSuccess(result.getData()).setNode(node()):
                GatewayResultMessage.buildError(AgreementConstants.ResponseCode._404.getCode(),
                        "网关协议调用失败！").setNode(node())
                );

        channel.writeAndFlush(response);

    }
    private String node(){
        return
                gatewaySessionFactory.getConfiguration().getHost() + ":" +
                        gatewaySessionFactory.getConfiguration().getPort();
    }
}
